package com.pet.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pet.constant.MessageConstant;
import com.pet.constant.StatusConstant;
import com.pet.context.BaseContext;
import com.pet.dto.web.UserInformationDTO;
import com.pet.dto.web.UserLoginDTO;
import com.pet.entity.Employee;
import com.pet.entity.UserInformation;
import com.pet.exception.AccountNotFoundException;
import com.pet.exception.PasswordErrorException;
import com.pet.exchange.DeleteUtil;
import com.pet.mapper.UserInformationMapper;
import com.pet.pageDto.PetAdoptPageDTO;
import com.pet.pageDto.UserInfoPageDTO;
import com.pet.result.PageResult;
import com.pet.service.UserInformationService;
import com.pet.vo.web.UserInformationVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.Objects;

@Service
@Slf4j
public class UserInformationServiceImpl implements UserInformationService {

    @Autowired
    private UserInformationMapper userInformationMapper;
    @Autowired
    private DeleteUtil deleteUtil;

    /**
     * 员工登录
     *
     * @param userLoginDTO
     * @return
     */
    public Employee login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = userInformationMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

//        if (Objects.equals(employee.getStatus(), StatusConstant.DISABLE)) {
//            //账号被锁定
//            throw new AccountNotFoundException(MessageConstant.ACCOUNT_LOCKED);
//        }
        //判断成功后修改数据库用户最近一次登录时间 修改表userInformation中的last_login字段为当前时间（date）
        userInformationMapper.updateLastLoginTime(LocalDateTime.now(), employee.getId());

        //3、返回实体对象
        return employee;
    }

    /**
     * 上传/修改主页背景
     * @param imgUrl
     */
    public void updateHomepageBackground(String imgUrl) {
        userInformationMapper.updateHomepageBackground(imgUrl, BaseContext.getCurrentId());
        return;
    }

    /**
     * 查询用户信息
     * @return
     */
    public UserInformationVO selectUserInformation(Integer userId) {
        if (userId == null){
            userId = Math.toIntExact(BaseContext.getCurrentId());
        }
        UserInformation entity = userInformationMapper.selectUserInformation(Long.valueOf(userId));
        UserInformationVO vo = new UserInformationVO();
        BeanUtils.copyProperties(entity,vo);
        vo.setCreateUserId(userId);

        return vo;
    }

    /**
     * 修改用户信息
     */
    public void updateUserInfo(UserInformationDTO dto) {
        UserInformation e = new UserInformation();
        BeanUtils.copyProperties(dto,e);
        e.setId(Math.toIntExact(BaseContext.getCurrentId()));
        userInformationMapper.updateUserInfo(e);
    }

    /**
     * 注册用户
     * @param userLoginDTO
     */
    public void insertUserInformation(UserLoginDTO userLoginDTO) {
        //声明
        UserInformation userInformation = new UserInformation();
        BeanUtils.copyProperties(userLoginDTO,userInformation);
        //加密
        userInformation.setPassword(DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes()));
        userInformation.setCreateTime(LocalDateTime.now());
        //添加
        userInformationMapper.insertUserInformation(userInformation);
        
    }

    /**
     * 修改密码
     * @param userLoginDTO
     */
    public void updatePassword(UserLoginDTO userLoginDTO) {
        userLoginDTO.setPassword(DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes()));
        log.info("修改密码:{}",userLoginDTO);
        //修改数据库
        userInformationMapper.updatePassword(userLoginDTO.getPassword(),BaseContext.getCurrentId());
    }

    /**
     * 分页查询所有用户信息
     * @param pageDTO
     * @return
     */
    public PageResult pageUserInformationAll(UserInfoPageDTO pageDTO) {
        Page<UserInformationVO> page = new Page<>();
        PageHelper.startPage(pageDTO.getPage(),pageDTO.getPageSize());
        try (Page<UserInformation> entityList = userInformationMapper.pageUserInformationAll(pageDTO)) {
            log.info("{}",entityList);
            for (UserInformation e : entityList) {
                UserInformationVO vo = new UserInformationVO();
                BeanUtils.copyProperties(e, vo);
                //设置用户id
                vo.setCreateUserId(e.getId());
                //处理头像
                //vo.setProfilePhoto(userInformationMapper.selectProfilePhotoById(e.getCreateUser()));
                page.add(vo);
            }
        }

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 删除用户信息
     * @param id
     */
    public void deleteUserInformation(Integer id) {
        //删除用户信息 以该用户的id为外键删除对应的帖子、收藏、点赞、评论、送养、领养、领养申请、宠物信息
        deleteUtil.deleteUserInformation(id);
        log.info("successfully delete");
    }

}
